// 模块化
import Vue from 'vue'
import VueRouter from 'vue-router'
// 明确的安装路由功能
Vue.use(VueRouter)

// 创建路由模块和配置路由
const router = new VueRouter({
  // 使用routes进行路由配置
  routes: [
    {
      name: 'default',
      path: '/',
      redirect: { name: 'index' }
    },
    {
      name: 'index',
      path: '/index',
      component: () => import('@/views/index.vue'),
      meta: { title: '首页', keepAlive: false }
    },
    {
      name: 'login',
      path: '/login',
      component: () => import('@/views/login.vue')
    },
    {
      name: 'register',
      path: '/register',
      component: () => import('@/views/register.vue')
    },
    {
      name: 'personal',
      // 配置路由参数
      path: '/personal/:id',
      component: () => import('@/views/personal.vue')
    },
    {
      name: 'personal',
      // 配置路由参数
      path: '/editUserInfo/:id',
      component: () => import('@/views/editUserInfo.vue')
    },
    {
      name: 'myfollows',
      // 配置路由参数
      path: '/myfollows',
      component: () => import('@/views/myfollows.vue'),
      meta: { keepAlive: false } // false为不缓存
    },
    {
      name: 'mystars',
      // 配置路由参数
      path: '/mystars',
      component: () => import('@/views/mystars.vue'),
      meta: { keepAlive: false } // false为不缓存
    },
    {
      name: 'articleDetail',
      // 配置路由参数
      path: '/articleDetail/:id',
      component: () => import('@/views/articleDetail.vue'),
      meta: { keepAlive: false, title: '文章详情' }, // false为不缓存
    },
    {
      name: 'comment',
      // 配置路由参数
      path: '/comment/:id',
      component: () => import('@/views/comment.vue'),
      meta: { keepAlive: false } // false为不缓存
    },
    {
      name: 'cateManager',
      path: '/cateManager',
      component: () => import('@/views/cateManager.vue')
    },
    {
      name: 'search',
      path: '/search',
      component: () => import('@/views/search.vue'),
      meta: { keepAlive: false } // false为不缓存
    }
  ]
})


// 添加全局的导航守卫--前置守卫，在跳转之前触发的
// 它的作用是限制用户的路由跳转，说白了，就是当前的路由到底能不能跳转，我们在跳转之前进行判断并处理
router.beforeEach((to, from, next) => {
  let arr = ['/personal', '/aa']
  console.log('我经过了导航守卫');
  // 我们需要判断一下用户当前目标路由是否是需要验证的路由
  if (to.path.indexOf('/personal') !== -1) {
    // 判断用户是否有合法的合法的登陆状态，如果有则继续跳转，如果没有则重定向到登陆
    let token = localStorage.getItem('toutiao_59_token')
    if (token) {
      next()
    } else {
      // next的参数与之前的$router.push方法的参数一致
      next({ name: 'login' })
    }
  } else {
    next() // 你随意
  }
})


router.afterEach((to, from) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
})

// 暴露
export default router